#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>

namespace Client
{
    using namespace std;
    class udpClient
    {
    public:
        udpClient(const string &serverip, const uint16_t &port)
            : _serverip(serverip), _serverport(port), _sockfd(-1), _quit(false)
        {
        }

        void initClient()
        {
            // 1、创建socket
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(1);
            }
            // 2、绑定，client要不要绑定? 要！需不需要程序员手动bind? 不需要！
            // 由os自动形成并绑定,只创建一个套接字就可以了，TCP也是如此
            cout << "socket success: " << " : " << _sockfd << endl;

        }

        void run()
        {
            struct sockaddr_in server;     // 在用户栈上定义了一个变量注意是in
            //bzero(&server, sizeof(server)); // 初始化为0
            memset(&server,0,sizeof(server));

            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport); // htons大小端转化
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            string message;
            char buffer1[1024];
            while (!_quit)
            {
                cout << "please Enter# ";
                //cin >> message;

                fgets(buffer1,sizeof(buffer1),stdin);

                message = buffer1;

                sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));

                char buffer[1024];

                struct sockaddr_in temp;
                socklen_t len = sizeof(temp);//必填

                ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&temp,&len);

                buffer[n]=0;

                cout<<"帅哥回应#### \n"<<buffer<<endl;
            }
        }

        ~udpClient()
        {

        }

    private:
        int _sockfd;
        string _serverip;
        uint16_t _serverport;
        bool _quit;
    };
}


